import {routerRedux} from 'dva/router'
import {login} from './service'
import {setToken} from 'utils/authority'

export default {
  namespace: 'login',

  state: {},

  effects: {
    * login ({
               payload,
             }, {put, call, select}) {
      const response = yield call(login, payload)
      const {locationQuery} = yield select(_ => _.app)

      if (response.code === 0) {
        const {from} = locationQuery
        const {data} = response

        setToken(data)

        yield put({type: 'app/query'})
        if (from && from !== '/login' && from !== '/') {
          yield put(routerRedux.push(from))
        } else {
          yield put(routerRedux.push('/'))
        }
      } else {
        throw response
      }
    },
  },

}
